<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70vw">
    <el-form size="large" ref="formRef" :model="formData" :rules="formRules" label-width="120px"
      v-loading="formLoading">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="申请单号" prop="repairNo">
            <el-input disabled v-model="formData.repairNo" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="故障分类" prop="faultId">
            <el-select clearable filterable v-model="formData.faultId" placeholder="请选择故障分类">
              <el-option v-for="dict in FaultClassificationList" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="故障发生时间" prop="faultTime">
            <el-date-picker v-model="formData.faultTime" type="datetime" value-format="x" placeholder="选择故障发生时间"
              :disabled-date="disabledDate" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="故障设备名称" prop="equipmentName">
            <el-select :loading="remortLoading" remote :remote-method="remoteSearch" clearable filterable
              v-model="formData.equipmentId" placeholder="请输入关键字搜索,支持设备名称、编码、安装位置">
              <el-option v-for="dict in EquipmentList" :key="dict.id"
                :label="`${dict.equipmentName} - ${dict.code} - ${dict.installPosition}`" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="故障设备型号" prop="equipmentModel">
            <el-input disabled v-model="formData.equipmentModel" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="设备所属部门" prop="deptName">
            <el-input disabled v-model="formData.deptName" />
          </el-form-item>
        </el-col>


        <el-col :span="8">
          <el-form-item label="申请人" prop="requestUserId">
            <el-select clearable filterable v-model="formData.requestUserId" placeholder="请选择申请人">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="申请人" prop="requestUserName">
            <el-input v-model="formData.requestUserName" placeholder="请输入申请人" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="formData.urgency" placeholder="请选择紧急程度">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.URGENCY)" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="维修人" prop="dutyUserId">
            <el-select clearable multiple filterable v-model="formData.dutyUserId" placeholder="请选择维修人">
              <el-option v-for="dict in userList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>


        <!-- <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.REPAIR_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col> -->

        <!-- <el-col :span="8">
          <el-form-item label="是否解决" prop="resolved">
            <el-input v-model="formData.resolved" placeholder="请输入是否解决" />
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="期望解决日期" prop="expectedResolveTime">
            <el-date-picker v-model="formData.expectedResolveTime" type="date" value-format="YYYY-MM-DD"
              placeholder="选择期望解决日期" :disabled-date="expectedDisabledDate" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="维修方式" prop="repairWay">
            <el-radio-group v-model="formData.repairWay">
              <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.REPAIR_TYPE)" :key="dict.value" :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="故障描述" prop="description">
            <Editor v-model="formData.description" height="150px" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { RepairRequestApi, RepairRequest } from '@/api/business/repairrequest'
import { FaultClassificationApi, FaultClassification } from '@/api/business/faultclassification'
import { EquipmentManageApi, EquipmentManage } from '@/api/business/equipmentmanage'
import * as UserApi from '@/api/system/user'
import { dateFormatter, formatDate } from '@/utils/formatTime'



/** 维修申请 表单 */
defineOptions({ name: 'RepairRequestForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  repairNo: undefined,
  faultId: undefined,
  faultName: undefined,
  equipmentModel: undefined,
  deptName: undefined,
  code: undefined,
  equipmentId: undefined,
  equipmentName: undefined,
  faultTime: undefined,
  requestUserId: undefined,
  requestUserName: undefined,
  urgency: undefined,
  description: undefined,
  repairWay: 1,
  dutyUserId: [],
  dutyUserName: undefined,
  status: undefined,
  resolved: undefined,
  expectedResolveTime: undefined
})
const formRules = reactive({
  faultId: [{ required: true, message: '故障分类不能为空', trigger: 'change' }],
  equipmentId: [{ required: true, message: '故障设备不能为空', trigger: 'blur' }],
  faultTime: [{ required: true, message: '故障发生时间不能为空', trigger: 'blur' }],
  requestUserId: [{ required: true, message: '申请人不能为空', trigger: 'blur' }],
  urgency: [{ required: true, message: '紧急程度不能为空', trigger: 'change' }],
  description: [{ required: true, message: '故障描述不能为空', trigger: 'blur' }],
  repairWay: [{ required: true, message: '维修方式不能为空', trigger: 'blur' }],
  dutyUserId: [{ required: true, message: '维修人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await initData()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RepairRequestApi.getRepairRequest(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RepairRequest
    if (formType.value === 'create') {
      await RepairRequestApi.createRepairRequest(data)
      message.success(t('common.createSuccess'))
    } else {
      await RepairRequestApi.updateRepairRequest(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    repairNo: undefined,
    faultId: undefined,
    faultName: undefined,
    equipmentModel: undefined,
    deptName: undefined,
    code: undefined,
    equipmentId: undefined,
    equipmentName: undefined,
    faultTime: undefined,
    requestUserId: undefined,
    requestUserName: undefined,
    urgency: undefined,
    description: undefined,
    repairWay: 1,
    dutyUserId: [],
    dutyUserName: undefined,
    status: undefined,
    resolved: undefined,
    expectedResolveTime: undefined
  }
  formRef.value?.resetFields()
}

//故障分类列表
const FaultClassificationList = ref([])

//设备列表
const EquipmentList = ref([])

//用户列表
const userList = ref([])

const remortLoading = ref(false)

const remoteSearch = async (query) => {
  console.log("?????", query);
  remortLoading.value = true
  let params = {
    keyWords: query
  }
  EquipmentList.value = await EquipmentManageApi.getEquipmentManageList(params)
  remortLoading.value = false
}


const initData = async () => {
  FaultClassificationList.value = await FaultClassificationApi.getFaultClassificationList();

  // EquipmentList.value = await EquipmentManageApi.getEquipmentManageList()

  userList.value = await UserApi.getSimpleUserList()

}

// 定义 disabledDate 函数 
const disabledDate = (time) => {
  // 禁用所有晚于当前时间的日期和时间
  return time.getTime() > Date.now();
}

// 禁用当前日期之前的日期
const expectedDisabledDate = (time) => {
  // 将当前时间归零（只比较日期部分）
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 禁用所有早于今天的日期
  return time.getTime() < today.getTime();
}

const selectEquipmentChange = (id) => {
  console.log("selectEquipmentChange", id);
  if (id) {
    // 根据 id 查找设备对象
    const selectedEquipment = EquipmentList.value.find(item => item.id === id);
    console.log("selectedEquipment", selectedEquipment);

    if (selectedEquipment) {
      console.log("?????");

      // 找到了，填充 formData
      formData.value.equipmentModel = selectedEquipment.equipmentModel;
      formData.value.deptName = selectedEquipment.deptName;
      // 其他字段也可以继续赋值
      // formData.xxx = selectedEquipment.xxx;
    } else {
      // 没找到匹配的设备
      formData.value.equipmentModel = undefined;
      formData.value.deptName = undefined;
    }
  } else {
    formData.value.equipmentModel = undefined
    formData.value.deptName = undefined
  }

}

</script>
